package Creator;

import listboxlib.pageutils.ListBoxSQLCreator;
import model.dto.ListConfigDTO;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StudentListCreator implements ListBoxSQLCreator {
    private final String replaceSql = "#USER_NAME_LIKE#";
    private final String filedName = "user_name";
    private String finalSql = null;

    @Override
    public String creator(List<ListConfigDTO> listConfigDTOS, String sql) {
        listConfigDTOS.stream().filter(listConfigDTO -> filedName.equals(listConfigDTO.getFieldName()))
                .forEach(listConfigDTO -> {
                    Optional<String> valueOpt = Arrays.asList(listConfigDTO.getFieldValue()).stream().findFirst();
                    if (valueOpt.isPresent()) {
                        String value = valueOpt.get();
                        StringBuffer replaceSqlBuffer = new StringBuffer("and ").append(filedName).append(" like ").append("'%").append(value).
                                append("%'");
                        finalSql = replaceSqlBuffer.toString();
                    }
                    listConfigDTO.setFieldValue(null);
                });
        if (!StringUtils.isEmpty(finalSql)) {
            return sql.replace(replaceSql, finalSql);
        } else {
            return sql.replace(replaceSql,"");
        }
    }
}
